package io.gitee.skyarthur1987.leporidae.utils.base;

import com.google.common.collect.Lists;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.TreeMap;

/**
 * List 工具类
 * Created by skyarthur on 2024/3/10
 */
public class ListUtils {
    /**
     * 按照固定组数均匀分组
     *
     * @param dataList 输入数据
     * @param groupNum 分组组数
     * @param <T>      元素类型
     * @return 均匀分组后的二维数组
     */
    public static <T> List<List<T>> partitionByFixedGroup(List<T> dataList, int groupNum) {
        if (CollectionUtils.isEmpty(dataList)) {
            return Lists.newArrayList();
        }
        Assert.isTrue(groupNum > 0, "groupNum must be larger than 0!");
        int i = 0;
        TreeMap<Integer, List<T>> idx2GroupList = new TreeMap<>();
        for (T data : dataList) {
            Integer idx = i % groupNum;
            if (!idx2GroupList.containsKey(idx)) {
                idx2GroupList.put(idx, Lists.newArrayList());
            }
            idx2GroupList.get(idx).add(data);
            i++;
        }
        return Lists.newArrayList(idx2GroupList.values());
    }
}
